<!doctype html>
<html>
<head>
	<meta charset="UTF-8">
    <!--<meta name="viewport" id="viewport"  content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no" >-->
    <meta name="viewport" content="width=320,maximum-scale=1.3,user-scalable=no">
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta content="email=no" name="format-detection">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <link rel="stylesheet" href="css/yy_h5.css">
    <title>录音发送</title>
    <style>
html,body{ width:100%; height:100%;}
.touch{ width:130px; height:130px;  position:relative; margin:auto; }
.touchanimate .spinner {width: 126px;height: 126px;background-color: #38c4a9; position:absolute; z-index:1; border-radius: 100%;-webkit-animation: scaleout 2.0s infinite ease-out;animation: scaleout 2.0s infinite ease-out;left:50%; top:50%;opacity: 0;left:2px; top:2px; }
.touchanimate .spinner2 {width: 120px;height: 120px;background-color: #4a9; position:absolute; z-index:10; border-radius: 100%;-webkit-animation: scaleout2 2.0s 0.4s infinite ease-out;animation: scaleout2 2.0s 0.4s infinite ease-out;left:50%; top:50%; opacity: 0;left:5px; top:5px; } 
.green_top{ width:90px; height:90px; border-radius:90px;background:#38c4a9; position:absolute; z-index:999; left:50%; top:50%; transform:translate(-45px,-45px);}
@-webkit-keyframes scaleout {
  0% { -webkit-transform: scale(0.5);opacity: 1; }
  100% {-webkit-transform: scale(1.0);opacity: 0;}
} 
@keyframes scaleout {
  0% {transform: scale(0.5);-webkit-transform: scale(0.5);opacity: 1;} 
  70%{opacity: 0.1;}
  100% {transform: scale(1.0);-webkit-transform: scale(1.0);opacity: 0;}
}
@keyframes scaleout2 {
  0% {transform: scale(0.5);-webkit-transform: scale(0.5);opacity: 1;} 
  70%{opacity: 0.1;}
  100% {transform: scale(1.0);-webkit-transform: scale(1.0);opacity: 0;}
}
/*circle*/
.step2{ display:block;}
.step3{padding-top: 16px; display:none;}
.circle_process{position:relative;width:93px;height:94px; margin:auto;}
.circle_process .wrapper{width:47px;height:94px;position:absolute;top:0;overflow:hidden}
.circle_process .center{ background:url(images/sanjiao.png) no-repeat 35px center #fff; background-size:30px 34px; width:92px; height:92px; border-radius:50%; border:1px solid #ccc; z-index:1}
.circle_process .right{right:0}
.circle_process .left{left:0}
.circle_process .circle{width:92px;height:92px;border:1px solid transparent;border-radius:50%;position:absolute;top:0;transform:rotate(-135deg)}
.circle_process .rightcircle{border-top:1px solid #38c4a9;border-right:1px solid #38c4a9;right:0;-webkit-animation:circle_right linear;}
.circle_process .leftcircle{border-bottom:1px solid #38c4a9;border-left:1px solid #38c4a9;left:0;-webkit-animation:circle_left linear;}
@-webkit-keyframes circle_right{0%{-webkit-transform:rotate(-135deg)}
100%,50%{-webkit-transform:rotate(45deg)}
}
@-webkit-keyframes circle_left{0%,50%{-webkit-transform:rotate(-135deg)}
100%{-webkit-transform:rotate(45deg)}
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
window.onerror=function(e){
  alert(e)
}
$(function(){
    var recordState='0';
    var startTime,timeout,timerid,
    recordlabel=$('#recordtime'),
    recordtime=$('#recordingtime'),
    recorder=$('#recorder'),
    playback=$('#recordplayback'),
    left=$('#leftcircle'),
    right=$('#rightcircle'),
    timer,
    play='0';
    
	$('.sound_partner dl').each(function() {
		$(this).find('dd').click(function(){
			$(this).parent('dl').remove();
		})			
	});

	recorder[0].addEventListener("touchstart",function(event){
	   event.preventDefault();
	   startTime=new Date().getTime();
	   timeout=setTimeout((function(value){
	      return function(){
         	   if(value===startTime&&recordState==='0'){
			      //开始录音
			      $('#touch').addClass('touchanimate');
			      recordState='1';//准备录音
			      timer=new Timer(recordlabel,function(){
			        recordState='2';//开始录音
			        recording=true;
                    navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
                       alert('error...'+e)
                    });
			      }).start(1000);
			   }
	      };
	   })(startTime),300);
	}, false); 
		
	recorder[0].addEventListener("touchend",function(event){
	   startTime=null;//清除点击播放起始时间
	   if(timer){
	      timer.stop();
	   }
       if(timeout)
          clearTimeout(timeout);
	   if(recordState==='2'){//录音结束,准备播放
	      recording=false;
	      test();
	      recordtime.text(recordlabel.text());
	      recorder.css('display','none');
	      playback.css('display','block');
	      recordState='3';//录音完毕，等待播放	
	   }else{
	   	  recordState='0';//初始状态
	   }	   
	}, false);
	
    $('#play')[0].addEventListener("touchstart",function(e){
   	   event.preventDefault();
       startTime=new Date().getTime();
       timeout=setTimeout((function(value){
	   return function(){
           if(value===startTime){
              timer=null;//清空之前的定时器
		      //开始录音
		      playback.css('display','none');
		      recordlabel.text('按住录音');
		      $('#touch').removeClass('touchanimate');		      
		      recorder.css('display','block');	
		      recordState='0';	  
		    }
        };
	   })(startTime),300);
	},false);
	
	$('#play')[0].addEventListener("touchend",function(e){
	   if(timeout)
          clearTimeout(timeout);
	   startTime=null;
	   if(recordState==='3'&&timer&&play==='0'){//录音完毕，等待播放
	      play='1';
	      if(!left.hasClass('leftcircle')){//播放效果被清除,需要添加播放样式
	         left.addClass('leftcircle');
	         right.addClass('rightcircle');
	      }
	      left.css('-webkit-animation-duration',timer.getSecond()+'s');
	      right.css('-webkit-animation-duration',timer.getSecond()+'s');
	      setTimeout(function(){//播放后清除播放效果
	        left.removeClass('leftcircle');
	        right.removeClass('rightcircle');
	        play='0';
	      },timer.getSecond()*1000); 
	   }
	   
	},false);
	
	function Timer(context,startCallback){
	   this.context=context;
	   this.second=0;
	   this.startCallback=startCallback;
	}
	
	Timer.prototype={
	   start:function(interval){
	      var timer=this;
	      this.timerid=setInterval(function(){
	         (function(){
		         if(this.second===0){
		        	 this.context.text('00:01');
		        	 this.second++;	         
		        	 if(this.startCallback)
		        	    this.startCallback();
		         }else{
		             this.second++;	         
				     var times=this.context.text().split(':');
				     if(times[1]==='59'){
				        times[1]='00';
				        minute=parseInt(times[0])+1;
				        times[0]=minute<10?('0'+minute):minute;
				     }else{
				        second=parseInt(times[1])+1;
				        times[1]=second<10?('0'+second):second;
				     }
				     this.context.text(times.join(':')); 
		         }
	         }).call(timer);
	      }, interval);
	      return this;
	   },
	   getSecond:function(){
	      return this.second;
	   },
	   stop:function(){
	      if(this.timerid)
	        clearInterval(this.timerid);	        
	   }
	};
	
	  var audio_context;
    try {
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;      
      audio_context = new AudioContext;
    } catch (e) {
      alert('No web audio support in this browser!');
    }
    
   var recBuffers=[[],[]],recLength=0,buffer = [],recording=false;
   function startUserMedia(stream) {
    if(!recording)return;
    var input = audio_context.createMediaStreamSource(stream);
    var context = input.context;
    var node = (context.createScriptProcessor || context.createJavaScriptNode).call(context, 4096, 2, 2);
    node.onaudioprocess = function (e) {
	   for (var channel = 0; channel<2; channel++) {
	       buffer.push(e.inputBuffer.getChannelData(channel));
	   }   
	   
	   for (var c = 0; c < 2; c++) {
        recBuffers[c].push(buffer[c]);
       }
       recLength += buffer[0].length;
    };
    input.connect(node);
    node.connect(input.context.destination); //this should not be necessar
  }
  
  function test(){
	   var buffers = [];
		  
	   for (var channel = 0; channel < 2; channel++) {
			buffers.push(mergeBuffers(recBuffers[channel], recLength));
	   }
		var interleaved = interleave(buffers[0], buffers[1]);  
		var dataview = encodeWAV(interleaved);
		var audioBlob = new Blob([dataview], { type: 'audio/wav' });
		
		
		var url = URL.createObjectURL(audioBlob);
		
      var li = document.createElement('li');
      var au = document.createElement('audio');
      var hf = document.createElement('a');
      
      au.controls = true;
      au.src = url;
      hf.href = url;
      hf.download = new Date().toISOString() + '.wav';
      hf.innerHTML = hf.download;
      li.appendChild(au);
      li.appendChild(hf);
      document.getElementById('recordingslist').appendChild(li);
		
		/**
		audio_context.decodeAudioData(audioBlob, function(b) {
			var source = audio_context.createBufferSource(); // creates a sound source
			source.buffer = b;    
			source.connect(audio_context.destination); // connect the source to the context's destination (the speakers)
			source.start(0);   
		}, function(err) { alert(err) });  **/
  }
  
          function mergeBuffers(recBuffers, recLength) {
                var result = new Float32Array(recLength);
                var offset = 0;
                for (var i = 0; i < recBuffers.length; i++) {
                    result.set(recBuffers[i], offset);
                    offset += recBuffers[i].length;
                }
                return result;
            }
            
            function interleave(inputL, inputR) {
                var length = inputL.length + inputR.length;
                var result = new Float32Array(length);

                var index = 0,
                    inputIndex = 0;

                while (index < length) {
                    result[index++] = inputL[inputIndex];
                    result[index++] = inputR[inputIndex];
                    inputIndex++;
                }
                return result;
            }
            
              function encodeWAV(samples) {
                var buffer = new ArrayBuffer(44 + samples.length * 2);
                var view = new DataView(buffer);

                /* RIFF identifier */
                writeString(view, 0, 'RIFF');
                /* RIFF chunk length */
                view.setUint32(4, 36 + samples.length * 2, true);
                /* RIFF type */
                writeString(view, 8, 'WAVE');
                /* format chunk identifier */
                writeString(view, 12, 'fmt ');
                /* format chunk length */
                view.setUint32(16, 16, true);
                /* sample format (raw) */
                view.setUint16(20, 1, true);
                /* channel count */
                view.setUint16(22, 2, true);
                /* sample rate */
                view.setUint32(24, audio_context.sampleRate, true);
                /* byte rate (sample rate * block align) */
                view.setUint32(28, audio_context.sampleRate * 4, true);
                /* block align (channel count * bytes per sample) */
                view.setUint16(32, 2 * 2, true);
                /* bits per sample */
                view.setUint16(34, 16, true);
                /* data chunk identifier */
                writeString(view, 36, 'data');
                /* data chunk length */
                view.setUint32(40, samples.length * 2, true);

                floatTo16BitPCM(view, 44, samples);

                return view;
            }
            
            function floatTo16BitPCM(output, offset, input) {
                for (var i = 0; i < input.length; i++, offset += 2) {
                    var s = Math.max(-1, Math.min(1, input[i]));
                    output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
                }
            }
            
            function writeString(view, offset, string) {
                for (var i = 0; i < string.length; i++) {
                    view.setUint8(offset + i, string.charCodeAt(i));
                }
            }

})
  

</script>
	
</head>
<body>
      <div id="recordingslist"></div>

<div class="header launch_header sound_header">
    	录音发送
    	<a  class="header_left"><img src="images/return.png" width="11" height="21"></a>
        <div class="header_right">记录</div>
    </div>
    <!--search-->
<div class="search sound_search">
  <input type="text" value="输入号码或点击右侧查找联系人">
  <div class="add"><img src="images/add_green.png" width="18" height="18"></div>
</div>
<p class="launch_tip sound_tip">已添加（4／100）</p>
<div class="sound_p">
    <div class="launch_partner sound_partner">
    	<dl>
    		<dt><h2>叶天</h2><span>17001090004</span></dt>
    		<dd><img src="images/sound_delete.png" width="17" height="17"></dd>
    	</dl>
        <dl>
    		<dt><h2>古丽</h2><span>17001090005</span></dt>
    		<dd><img src="images/sound_delete.png" width="17" height="17"></dd>
    	</dl>
        <dl>
    		<dt><h2>叶天</h2><span>17001090004</span></dt>
    		<dd><img src="images/sound_delete.png" width="17" height="17"></dd>
    	</dl>
        <dl>
    		<dt><h2>古丽</h2><span>17001090005</span></dt>
    		<dd><img src="images/sound_delete.png" width="17" height="17"></dd>
    	</dl>
        <dl>
    		<dt><h2>陈坤</h2><span>15219800767</span></dt>
    		<dd><img src="images/sound_delete.png" width="17" height="17"></dd>
    	</dl>
        <dl>
    		<dt><h2>舒淇</h2><span>13897652234</span></dt>
    		<dd><img src="images/sound_delete.png" width="17" height="17"></dd>
    	</dl>
    </div>
    </div>
    <div class="sound_touch">    	
        <!--step1、step2-->  
        <div class="step2" id="recorder"> 
        	<div class="sound_time" id="recordtime">按住录音</div> 
            <div class="touch" id="touch"><!--添加类touchanimate--> 	
                <div class="green_top"><img src="images/voice.png" width="90" height="90"></div>
                <div class="spinner"></div>
                <div class="spinner2"></div>
            </div>
        </div>   
        <!--step1、step2-->
        <!--step3-->
        <div class="step3" id="recordplayback">
            <div class="sound_time_step3" id="recordingtime"></div> 
            <div class="circle_process" id="play">
                <div class="wrapper right">
                    <div class="circle rightcircle" id="rightcircle"></div>
                </div>
                <div class="center"></div>
                <div class="wrapper left">
                    <div class="circle leftcircle" id="leftcircle"></div>
                </div>
            </div>
            <p style=" height:25px; line-height:25px; text-align:center; font-size:10px; color:#adadad;">点击试听 长按重录</p>
        </div>
        <!--step3-->
       
    </div>
    <div class="sound_footer"><span>定时发送</span><span>发起留言</span></div>
    
    
</body>
</html>